/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views.GestionRestaurateur;

import Controller.Controller;
import Model.Restaurateur;
import Views.GestionRestaurateur.RestaurateurPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;

/**
 *
 * @author ibrahim
 */
public class RestaurateurFrame extends JFrame {
    private static final String title = "Gestion de Restaurateurs";
   // private ToolBar myToolBar;
    private RestaurateurPanel restaurateurPanel;
    private RestaurateurTablePanel tablePanel;
    private JFileChooser jfileChooser;
    private Controller controller;
    private PreferenceDialog prefDialog;
    private Preferences prefs;
    
    public RestaurateurFrame() {
        super("Gestion de Restaurateurs");
        setMinimumSize(new Dimension(500, 400));
         
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setLayout(new BorderLayout());
        setJMenuBar(createMenuBar());
        this.restaurateurPanel = new RestaurateurPanel();
        this.tablePanel = new RestaurateurTablePanel();
        this.jfileChooser = new JFileChooser();
        this.jfileChooser.addChoosableFileFilter(new RestaurateurFileFilter());
        this.controller = new Controller();
        this.prefDialog = new PreferenceDialog(this);
        this.prefs = Preferences.userRoot().node("db");

        
        this.tablePanel.setRestaurateurTableListener(new RestaurateurTableListener() {

            @Override
            public void rowDeleted(int row) {
               int id = controller.getRestaurateurId(row);
               System.out.println(id);
               int action = JOptionPane.showConfirmDialog(RestaurateurFrame.this, 
                "Do you really want to remove this item from database ?", 
                "Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
                if(action == JOptionPane.OK_OPTION){
               try {
                    controller.deleteRestaurateurFromDatabase(id);
                } catch (SQLException ex) {
                    Logger.getLogger(RestaurateurFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                controller.removeRestaurateur(row);
                
               
            
                }
            }
        });

        this.restaurateurPanel.setAddRestaurateurListener(new AddRestaurateurListener() {
            @Override
            public void AddRestaurateurEventOccurred(AddRestaurateurEvent e) {
    
                controller.saisirInformationRestaurateur(e);
                tablePanel.refresh();
//                
                System.out.println(e.getPermanantCode());
                System.out.println(e.isCitizen());
            }
        });
        this.restaurateurPanel.setSaveToDatabaseListener(new SaveToDatabaseListener() {

            @Override
            public void savetodatabaseEventOccured() {
                     
               try {
                   controller.saveRestaurateurToDatabase();
                   if (controller.getResultAction().equals("Insertion")){
                       JOptionPane.showMessageDialog(RestaurateurFrame.this,"Item(s) Successfully Added to Database !");
                   }
                   else{
                       JOptionPane.showMessageDialog(RestaurateurFrame.this,"Item(s) Successfully Updated in Database !");
                   }
                   
                   
                 
              } catch (SQLException ex) {
                 JOptionPane.showMessageDialog(RestaurateurFrame.this,"Cannot Insert Data to Database", "Database Connection Error", JOptionPane.ERROR_MESSAGE);
  
              }
            }
        });
        this.restaurateurPanel.setLoadFromDatabaseListener(new LoadFromDatabaseListener() {

            @Override
            public void loadfromdatabaseEventOccured() {
                try {
                    controller.startDatabaseConnection();
                    System.out.println("Starting Database Connection");
                } catch (Exception ex) {
                   JOptionPane.showMessageDialog(RestaurateurFrame.this,"Cannot connect to database", "Database Connection Error", JOptionPane.ERROR_MESSAGE);
                }
    
               try {
                    controller.loadRestaurateursFromDatabase();
                    tablePanel.refresh();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(RestaurateurFrame.this,"Cannot Load Data from Database", "Database Connection Error", JOptionPane.ERROR_MESSAGE);
                }
                
            }
        });


addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("Window closing");
                System.out.println("closing database connection");
                try {
                    controller.closeDatabaseConnection();
                } catch (SQLException ex) {
                    System.out.println("Cannot Close Database Connection");
                }
                dispose();
                System.gc();
            }
    
});

this.tablePanel.setData(this.controller.getRestauraterurs());
this.prefDialog.setPreferencelistener(new PreferenceListener() {

            @Override
            public void preferenceSet(String username, String password, int port) {
               prefs.put("username", username);
               prefs.put("password", password);
               prefs.putInt("port", port);
            }
        });
        String user = prefs.get("username", "");
        String password = prefs.get("password", "");
        int port = prefs.getInt("port", 3306);
        prefDialog.setDefaultPreferences(user, password, port);
        add(this.restaurateurPanel, BorderLayout.WEST);
        add(new JScrollPane(tablePanel), BorderLayout.CENTER);

        
    }
    public void commencerAjoutNewRestaurateur(){
        setVisible(true);
    }

    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        //File Menu
        JMenu fileMenu = new JMenu("File");
        JMenuItem exportDataItem = new JMenuItem("Export Data...");
        exportDataItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(jfileChooser.showSaveDialog(RestaurateurFrame.this)==JFileChooser.APPROVE_OPTION){
                    try {
                        controller.saveRestaurateurToFile(jfileChooser.getSelectedFile());
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(RestaurateurFrame.this,
                                "Could not save data to file.", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        JMenuItem importDataItem = new JMenuItem("Import Data...");
        importDataItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK));
        importDataItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(jfileChooser.showOpenDialog(RestaurateurFrame.this)==JFileChooser.APPROVE_OPTION){
                    try {
                        controller.loadRestaurateurFromFile(jfileChooser.getSelectedFile());
                        tablePanel.refresh();
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(RestaurateurFrame.this,
                                "Could not laod data from file.", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.setMnemonic(KeyEvent.VK_X);
        exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int action = JOptionPane.showConfirmDialog(RestaurateurFrame.this, 
                "Do you really want to exit the application ?", 
                "Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
                if(action == JOptionPane.OK_OPTION){
                    WindowListener[] listeners =getWindowListeners();
                    for(WindowListener listener:listeners){
                        listener.windowClosing(new WindowEvent(RestaurateurFrame.this,0));
                    }
              
                }
                
            }
        });
        fileMenu.add(exportDataItem);
        fileMenu.add(importDataItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        //Window Menu
        JMenu windowMenu = new JMenu("Window");
        JMenuItem windowMenuItem = new JMenuItem("Preferences");
        windowMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK));
        windowMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                prefDialog.setVisible(true);
            }
        });
        JMenu showMenu = new JMenu("Show");
        JCheckBoxMenuItem showMenuItem = new JCheckBoxMenuItem("Restaurateur Form");
        showMenuItem.setSelected(true);
        showMenuItem.addActionListener(new ActionListener() {
            //Hiding Unhiding the Restaurateur Panel
            @Override
            public void actionPerformed(ActionEvent ev) {
                JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) ev.getSource();
                restaurateurPanel.setVisible(menuItem.isSelected());

            }
        });
        
        windowMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                
            }
        });

        showMenu.add(showMenuItem);
        windowMenu.add(showMenu);
        windowMenu.add(windowMenuItem);

        menuBar.add(fileMenu);
        menuBar.add(windowMenu);
        return menuBar;
    }

    private void loadDataFromDatabase() throws Exception {
         controller.startDatabaseConnection();
         controller.loadRestaurateursFromDatabase();
        
    }
    
    
    
    
}
